<template>
  <div class="app-container">
    <el-row :gutter="20" class="div-height-left">
      <el-col v-if="userInfo.userId === '1'" :span="4" class="div-height-left">
        <sys-org-tree @treeClick="treeClick"/>
      </el-col>
      <el-col :span="userInfo.userId === '1' ? 20 : 24" :xs="24">
        <div class="search-container">
          <el-form
            v-show="showSearch"
            ref="queryParamsRef"
            :inline="true"
            :model="queryParams"
            label-width="160px"
          >
            <el-form-item label="自定义服务名称" prop="roleGroupName">
              <el-input
                v-model="queryParams.roleGroupName"
                clearable
                placeholder="请输入自定义服务"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <!-- <el-form-item label="自定义服务权限字符串" prop="roleKey">
              <el-input
                v-model="queryParams.roleKey"
                clearable
                placeholder="请输入自定义服务权限字符串"
                @keyup.enter.native="handleQuery"
              />
            </el-form-item> -->
            <div style="float: right" class="mr20">
              <query-form-button @handleQuery="handleQuery" @resetQuery="resetQuery"/>
            </div>
          </el-form>
        </div>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPerm="['system:roleGroup:add']"
              plain
              type="primary"
              @click="handleAdd"
            >
              <template #icon>
                <i-ep-plus/>
              </template>
              新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPerm="['system:roleGroup:remove']"
              :disabled="multiple"
              plain
              type="danger"
              @click="handleDelete"
            >
              <template #icon>
                <i-ep-delete/>
              </template>
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPerm="['system:roleGroup:export']"
              plain
              type="warning"
              @click="handleExport"
            >
              <template #icon>
                <i-ep-download/>
              </template>
              导出
            </el-button>
          </el-col>
        </el-row>

        <el-table
          v-adaptive
          :data="groupList"
          :border="true"
          highlight-current-row
          :stripe="true"
          :header-cell-style="$headerCellStyle"
        >
          <el-table-column
            :align="'center'"
            label="自定义服务名称"
            prop="roleGroupName"
          />
          <!-- <el-table-column
            :align="'center'"
            label="自定义服务权限字符串"
            prop="roleKey"
          /> -->
          <el-table-column :align="'center'" label="显示顺序" prop="roleSort"/>
          <el-table-column :align="'center'" label="自定义服务状态" prop="status">
            <template #default="scope">
              <el-switch
                v-model="scope.row.status"
                active-value="0"
                inactive-value="1"
                @change="handleStatusChange(scope.row)"
              ></el-switch>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" label="备注" prop="remark"/>
          <el-table-column
            :align="'center'"
            class-name="small-padding fixed-width"
            label="操作"
          >
            <template #default="scope">
              <el-button
                v-hasPerm="['system:roleGroup:edit']"
                type="success"
                @click="handleUpdate(scope.row)"
              >
                <template #icon>
                  <i-ep-edit/>
                </template>
                修改
              </el-button>
              <el-button
                v-hasPerm="['system:roleGroup:remove']"
                type="danger"
                @click="handleDelete(scope.row)"
              >
                <template #icon>
                  <i-ep-delete/>
                </template>
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="total > 0"
          v-model:limit="queryParams.pageSize"
          v-model:page="queryParams.pageNum"
          :total="total"
          @pagination="getList"
        />
      </el-col>
    </el-row>

    <!-- 添加或修改自定义服务信息对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :title="title"
      v-model="open"
      append-to-body
      width="600px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="170px">
        <el-form-item label="自定义服务名称" prop="roleGroupName">
          <el-input v-model="form.roleGroupName" placeholder="请输入自定义服务"/>
        </el-form-item>
        <!-- <el-form-item label="自定义服务权限字符串" prop="roleKey">
          <el-input v-model="form.roleKey" placeholder="请输入自定义服务权限字符串" />
        </el-form-item> -->
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input v-model="form.roleSort" placeholder="请输入显示顺序" type="number"/>
        </el-form-item>
        <el-form-item label="菜单权限">
          <div style="height: 440px; overflow-y: auto">
            <el-checkbox
              v-model="menuExpand"
              @change="handleCheckedTreeExpand($event, 'menu')"
            >展开/折叠
            </el-checkbox>
            <el-checkbox
              v-model="menuNodeAll"
              @change="handleCheckedTreeNodeAll($event, 'menu')"
            >全选/全不选
            </el-checkbox>
            <el-checkbox
              v-model="form.menuCheckStrictly"
              @change="handleCheckedTreeConnect($event, 'menu')"
            >父子联动
            </el-checkbox>
            <el-tree
              ref="menu"
              :check-strictly="!form.menuCheckStrictly"
              :data="menuOptions"
              :props="defaultProps"
              class="tree-border"
              default-expand-all
              empty-text="加载中，请稍候"
              node-key="id"
              show-checkbox
            ></el-tree>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入内容" type="textarea"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {addGroup, deleteVerify, delGroup, getGroup, listGroup, updateGroup} from "@/api/system/group";
import {selectMenuListByRoleGroupId, treeselect} from "@/api/system/menu";
import {changeRoleStatus} from "@/api/system/role";
import {useUserStoreHook} from "@/store/modules/user";

const useUserStore = useUserStoreHook();
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;

const menu = ref();
const formRef = ref();
const menuExpand = ref(true);
const menuNodeAll = ref(false);
// 按钮loading
const buttonLoading = ref(false);
// 显示搜索条件
const showSearch = ref(true);
// 总条数
const total = ref(0);
// 自定义服务信息表格数据
const groupList = ref([]);
// 弹出层标题
const title = ref("");
// 是否显示弹出层
const open = ref(false);
// 查询参数
const queryParamsRef = ref();
const queryParams = ref<SysRoleGroup>({
  pageNum: 1,
  pageSize: 10,
  roleGroupName: "",
  roleKey: "",
  status: "",
});
// 表单参数
const form = ref<SysRoleGroup>({});
// 菜单列表
const menuOptions = ref([]);
const defaultProps = ref({
  children: "children",
  label: "label",
});

// 表单校验
const rules = ref({
  roleGroupId: [{required: true, message: "自定义服务主键不能为空", trigger: "blur"}],
  roleGroupName: [{required: true, message: "自定义服务不能为空", trigger: "blur"}],
  // roleKey: [
  //     {required: true, message: "自定义服务权限字符串不能为空", trigger: "blur"}
  // ],
  roleSort: [{required: true, message: "显示顺序不能为空", trigger: "blur"}],
  status: [{required: true, message: "自定义服务状态不能为空", trigger: "blur"}],
});

if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId;
  getList();
}

/** 左侧科室树节点点击事件 */
function treeClick(obj: any) {
  queryParams.value.orgId = obj.id;
  getList();
}

/** 根据自定义服务ID查询菜单树结构 */
function selectMenuListByRoleGroupIdFun(roleGroupId) {
  return selectMenuListByRoleGroupId(roleGroupId).then((response) => {
    menuOptions.value = response.data.menus;
    return response;
  });
}

// 角色状态修改
function handleStatusChange(row: any) {
  let text = row.status === "0" ? "启用" : "停用";
  ElMessageBox.confirm('确认要"' + text + '""' + row.roleName + '"自定义服务吗？', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(function () {
      changeRoleStatus(row.roleId, row.status).then(() => {
        ElMessage.success(text + "成功");
      });
    })
    .catch(function () {
      row.status = row.status === "0" ? "1" : "0";
    });
}

// 树权限（展开/折叠）
function handleCheckedTreeExpand(value, type) {
  if (type === "menu") {
    let treeList: any = menuOptions.value;
    for (let i = 0; i < treeList.length; i++) {
      menu.value.store.nodesMap[treeList[i].id].expanded = value;
    }
  }
}

// 树权限（全选/全不选）
function handleCheckedTreeNodeAll(value, type) {
  if (type === "menu") {
    menu.value.setCheckedNodes(value ? menuOptions.value : []);
  }
}

// 树权限（父子联动）
function handleCheckedTreeConnect(value, type) {
  if (type === "menu") {
    form.value.menuCheckStrictly = value ? true : false;
  }
}

/** 查询菜单树结构 */
function getMenuTreeselect() {
  treeselect().then((response) => {
    menuOptions.value = response.data;
  });
}

// 所有菜单节点数据
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  let checkedKeys = menu.value.getCheckedKeys();
  // 半选中的菜单节点
  let halfCheckedKeys = menu.value.getHalfCheckedKeys();
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
  return checkedKeys;
}

/** 查询自定义服务信息列表 */
function getList() {
  listGroup(queryParams.value).then((response: any) => {
    groupList.value = response.rows;
    total.value = response.total;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    roleGroupId: "",
    roleGroupName: "",
    roleKey: "",
    roleSort: 0,
    status: "0",
    remark: "",
    menuCheckStrictly: true,
    orgId: userInfo.orgId,
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  queryParamsRef.value.resetFields();
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  getMenuTreeselect();
  open.value = true;
  title.value = "添加自定义服务信息";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const roleGroupId = row.roleGroupId;
  const roleGroupMenu = selectMenuListByRoleGroupIdFun(roleGroupId);
  getGroup(roleGroupId).then((response) => {
    form.value = response.data;
    open.value = true;
    nextTick(() => {
      roleGroupMenu.then((res) => {
        let checkedKeys = res.data.checkedKeys;
        checkedKeys.forEach((v) => {
          nextTick(() => {
            menu.value.setChecked(v, true, false);
          });
        });
      });
    });
    title.value = "修改自定义服务信息";
  });
}

/** 提交按钮 */
function submitForm() {
  (formRef.value as any).validate((valid) => {
    if (userInfo.orgId) {
      form.value.orgId = userInfo.orgId;
    }
    if (valid) {
      buttonLoading.value = true;
      form.value.orgId = queryParams.value.orgId;
      if (form.value.roleGroupId != "") {
        form.value.menuIds = getMenuAllCheckedKeys();
        updateGroup(form.value)
          .then((_response) => {
            ElMessage.success("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      } else {
        form.value.menuIds = getMenuAllCheckedKeys();
        addGroup(form.value)
          .then((_response) => {
            ElMessage.success("修改成功");
            open.value = false;
            getList();
          })
          .finally(() => {
            buttonLoading.value = false;
          });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const roleGroupId = row.roleGroupId;
  deleteVerify(roleGroupId).then((res: any) => {
    let showMsg = res.msg;
    if (!showMsg) {
      showMsg = "是否确认删除自定义服务信息吗？"
    }
    ElMessageBox.confirm(
      `${showMsg}`,
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        delGroup(roleGroupId).then(() => {
          getList();
          ElMessage.success("删除成功");
        });
      })
      .catch(() => {
      });
  })

}

/** 导出按钮操作 */
function handleExport() {
  // this.download('system/group/export', {
  //     ...this.queryParams
  // }, `group_${new Date().getTime()}.xlsx`)
}
</script>
<script lang="ts">
export default {
  name: "Group",
};
</script>
